<?php
	header( "Content-Type:text/html; charset=utf-8" );
	set_time_limit(0);
	require_once("config.inc.php");
	require_once("charset.func.php");
	require_once("db.class.php");
	
	$startyear = 2000;
	$fields = array(
		'year'=>urlencode('2010'),
		'mm'=>urlencode('1')
	);
	$url = 'http://www.nongli.com/item3/index.asp';
	echo "*** get cal start.***<br/>\n";
	for($y = $startyear;$y<$startyear+100;$y++) {
		$db = new db($site_Db);
		for($m = 1;$m<13;$m++) {
			$fields['year'] = urlencode(strval($y));
			$fields['mm'] = urlencode(strval($m));
			$fields_string = '';
			//url-ify the data for the POST
			foreach($fields as $key=>$value) {
				$fields_string .= $key.'='.$value.'&';
			}
			rtrim($fields_string ,'&');
			//echo $fields_string;
			//ob_start
			ob_start();
			//open connection
			$ch = curl_init();
			//set the url, number of POST vars, POST data 
			curl_setopt($ch, CURLOPT_URL,$url);
			curl_setopt($ch, CURLOPT_POST,count($fields));
			curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
			//execute post
			curl_exec($ch);
			
			$result=ob_get_contents();
			ob_end_clean();
			//提取万年历信息
			//$result = read_File('./r.txt');
			//write_File('./r.txt',$result);
			$result = gb2utf8($result);
			/*
			 * <p class="size2"><b>公历 1600 年 1 月　农历　己亥年　生肖：猪 
                      </b> </p>小寒:1600年1月6日&nbsp;06:13时&nbsp;&nbsp;&nbsp;&nbsp;大寒:1600年1月20日&nbsp;23:44时

			 */
			preg_match_all("/<p\sclass=\"size2\"><b>公历.+?农历(.+?)生肖：(.+?)\n\s+?<\/b>\s<\/p>(.+?)\n/u",$result,$i,PREG_SET_ORDER);
			
			$nl = trim($i[0][1]);
			$sx = trim($i[0][2]);
			
			if(!empty($nl) && !empty($sx)) {
				$info=preg_replace("/(&nbsp;)+/", " ", $i[0][3]);
				$month = $y.'-'.$m;
				//echo "REPLACE INTO month VALUES('{$month}', ".trim($i[1])."', ".trim($i[2])."', '".trim($info)."')";
				if($db->query("REPLACE INTO month VALUES('{$month}', '{$nl}', '{$sx}', '".trim($info)."')"))
					echo "********* Add a new month $month.<br/>\n";
			}
		}
		$db->close();
		echo "*** Add a new year {$y}.<br/>\n";
		sleep(2);
	}
	
?>